<?php
namespace Authentication\Service;

use Zend\Authentication\Storage\StorageInterface;
use User\Repository\UserRepository;

class UserIdStorage implements StorageInterface {
    /**
     *
     * @var StorageInterface
     */
    private $storage;
    
    /**
     * @var UserRepository 
     */
    private $userRepository;
    
    /**
     * @var \User\Entity\User
     */
    private $user;
    
    public function init() {
        if(!$this->storage->isEmpty()) {
            $userId = $this->storage->read();
            $this->user = $this->userRepository->find($userId);
            
            if(!$this->user) {
                $this->storage->clear();
            }
        }
    }
    
    public function clear() {
        $this->user = null;
        $this->storage->clear();
    }

    public function isEmpty() {
        return !$this->user;
    }

    public function read() {
        return $this->user;
    }

    public function write($user) {
        $this->user = $user;
        $this->storage->write($user->getId());
    }
    
    public function setStorage(StorageInterface $storage) {
        $this->storage = $storage;
    }
    
    public function setUserRepository(UserRepository $userRepository) {
        $this->userRepository = $userRepository;
    }
}